<template>
    <view class="container">
        <!-- 顶部导航栏（与其他页面一致） -->
        <view class="header">
            <view class="logo">logo</view>
            <searchbox :placeholder="'搜索'" @search="onSearch" />
        </view>

        <view class="content">
            <view class="section">
                <text class="section-title">最近播放</text>
                <view class="song-list" v-if="!loading && historySongs.length">
                    <view class="song-item" 
                          v-for="(song, index) in historySongs.slice(0, 6)" 
                          :key="song.id || index"
                          @click="playSong(song)">
                        <image :src="song.cover_url || '/static/logo.png'" class="song-image" />
                        <view class="song-info">
                            <text class="song-title">{{ song.title }}</text>
                            <text class="song-artist">{{ song.artist }}</text>
                            <text class="song-time">{{ formatTime(song.last_played || song.played_at) }}</text>
                        </view>
                        <view class="song-more" @click.stop="showSongMenu(song)">
                            <text class="icon">···</text>
                        </view>
                    </view>
                </view>
                <view class="empty" v-if="!loading && !historySongs.length">
                    <text>暂无播放记录</text>
                </view>
                <view class="loading" v-if="loading">
                    <text>加载中...</text>
                </view>
            </view>
        </view>

        <!-- 底部播放器 -->
        <music-player 
            :song="currentSong"
            @previous="previousSong"
            @next="nextSong"
        />
    </view>
    </template>

<script>
import MusicPlayer from '@/components/music-player/music-player.vue'
import SearchBox from '@/components/searchbox/searchbox.vue'

export default {
    components: { MusicPlayer, SearchBox },
    data() {
        return {
            userId: 'user_001',
            loading: false,
            allHistorySongs: [],
            historySongs: [],
            currentSong: null
        }
    },
    onLoad() {
        this.loadHistory();
    },
    onShow() {
        // 每次显示页面时刷新历史记录，实现实时更新
        this.loadHistory();
    },
    methods: {
        async loadHistory() {
            this.loading = true;
            try {
                // 直接从本地存储读取播放历史，避免接口不可用导致失败
                const history = uni.getStorageSync('playHistory') || [];
                // 将本地字段 playTime 兼容为 last_played 供 UI 使用
                const normalized = history.map(item => ({
                    ...item,
                    last_played: item.playTime
                }));
                this.allHistorySongs = normalized;
                this.historySongs = normalized;
                if (this.historySongs.length && !this.currentSong) {
                    this.currentSong = this.historySongs[0];
                }
            } catch (e) {
                uni.showToast({ title: '加载历史失败', icon: 'none' });
            } finally {
                this.loading = false;
            }
        },
        onSearch(keyword) {
            const key = (keyword || '').trim().toLowerCase();
            if (!key) {
                this.historySongs = this.allHistorySongs;
                return;
            }
            this.historySongs = this.allHistorySongs.filter(s => {
                return (s.title || '').toLowerCase().includes(key) || (s.artist || '').toLowerCase().includes(key);
            });
        },
        playSong(song) {
            this.currentSong = song;
        },
        previousSong() {
            const idx = this.historySongs.findIndex(s => s.id === this.currentSong.id);
            const prev = idx > 0 ? idx - 1 : this.historySongs.length - 1;
            this.currentSong = this.historySongs[prev];
        },
        nextSong() {
            const idx = this.historySongs.findIndex(s => s.id === this.currentSong.id);
            const next = idx < this.historySongs.length - 1 ? idx + 1 : 0;
            this.currentSong = this.historySongs[next];
        },
        showSongMenu(song) {
            uni.showActionSheet({
                itemList: ['播放', '添加到收藏', '查看详情'],
                success: (res) => {
                    if (res.tapIndex === 0) this.playSong(song);
                    if (res.tapIndex === 1) this.addToFavorites(song);
                    if (res.tapIndex === 2) this.showSongDetail(song);
                }
            });
        },
        async addToFavorites(song) {
            try {
                await uni.request({
                    url: 'http://localhost:3000/api/favorite/favorites',
                    method: 'POST',
                    data: { user_id: this.userId, song_id: song.id }
                });
                uni.showToast({ title: '已添加到收藏', icon: 'success' });
            } catch (e) {
                uni.showToast({ title: '添加收藏失败', icon: 'none' });
            }
        },
        showSongDetail(song) {
            uni.showModal({
                title: song.title,
                content: `艺术家: ${song.artist}`,
                showCancel: false
            });
        },
        formatTime(val) {
            if (!val) return '';
            const d = new Date(val);
            const y = d.getFullYear();
            const m = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            const hh = String(d.getHours()).padStart(2, '0');
            const mm = String(d.getMinutes()).padStart(2, '0');
            return `${y}-${m}-${day} ${hh}:${mm}`;
        }
    }
}
</script>

<style>
.container {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    position: relative;
}

.header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 90rpx;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10rpx);
    z-index: 50;
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
}

.logo {
    font-size: 32rpx;
    font-weight: bold;
    color: #667eea;
}

.content {
    margin-top: 90rpx;
    margin-bottom: 120rpx;
    padding: 30rpx;
}

.section {
    margin-bottom: 40rpx;
}

.section-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 30rpx;
    display: block;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.song-list {
    display: flex;
    flex-direction: column;
}

.song-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fe 100%);
    border-radius: 16rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(102, 126, 234, 0.1);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.song-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(118, 75, 162, 0.08) 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.song-item:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.25);
}

.song-item:active::before {
    opacity: 1;
}

.song-image {
    width: 110rpx;
    height: 110rpx;
    border-radius: 16rpx;
    margin-right: 24rpx;
    object-fit: cover;
    position: relative;
    z-index: 1;
}

.song-info {
    flex: 1;
    position: relative;
    z-index: 1;
}

.song-title {
    font-size: 30rpx;
    font-weight: bold;
    display: block;
    color: #2c3e50;
    margin-bottom: 8rpx;
}

.song-artist {
    font-size: 24rpx;
    color: #95a5a6;
    display: block;
    margin-bottom: 4rpx;
}

.song-time {
    font-size: 22rpx;
    color: #bdc3c7;
}

.song-more {
    width: 70rpx;
    height: 70rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 1;
}

.icon {
    font-size: 32rpx;
    color: #95a5a6;
    font-weight: bold;
}

.loading, .empty {
    text-align: center;
    padding: 40rpx 0;
    color: rgba(255, 255, 255, 0.8);
    font-size: 28rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 16rpx;
    backdrop-filter: blur(10rpx);
}
</style>
